<?php
namespace ac\modules\member\controllers;

use Yii;
use ac\controllers\BasicController;
use yii\web\Controller;
use app\modules\member\models\Member;
use app\modules\member\models\MemberMessage;
use common\component\exception\ErrMap;
use common\component\tool\Tool;
use common\models\OperationLog;

class MessageController extends BasicController
{
    protected $memberInfo;//登录信息

    public function init()
    {
        parent::init();
        if(isset($this->session->get('memberInfo')->loginname)){
            $this->memberInfo = $this->session->get('memberInfo');
        };
    }

    /*添加消息*/
    public function actionAddMessage()
    {
        if(Yii::$app->request->isPost 
            and isset($this->post['member_id']) 
            and isset($this->post['appid']) 
            and isset($this->post['secretkey'])
            and $this->post['secretkey'] == $this->params['secretkey']['ac']){

            $member = Member::find()->select(['member_id'])
                            ->where('member_id = :id and appid = :appid', [':id' => $this->post['member_id'], ':appid' => $this->post['appid']])
                            ->one();
            // P($member);
            if(!is_null($member)){
                $transaction = Yii::$app->db->beginTransaction();//事物处理
                $pass = true;
                try{
                    /*1、增加会员消息数量*/
                    if($pass){
                        if( !Member::updateAllCounters(['unread_messages' => 1], 'member_id = :memberid', [':memberid' => $member->member_id]) ){
                            $pass = false;
                            $backInfo = ErrMap::getError(10027);//返回信息
                        }
                    }

                    /*2、增加消息*/
                    if($pass){
                        $memberMessage = new MemberMessage;
                        $data = array(
                            'MemberMessage' => $this->post
                        );
                        $data['MemberMessage']['member_id'] = $member->member_id;
                        if(!$memberMessage->addMes($data)){
                            $pass = false;
                            if($memberMessage->hasErrors()){
                                $backInfo = ErrMap::getError(10005);//返回信息
                                $exception = $memberMessage->getErrors();//异常信息
                            }
                        }
                    }

                    if($pass){
                        $backInfo = [0, '添加会员消息成功'];//返回信息
                        $transaction->commit();
                    }
                }catch(\Exception $exception){
                    $transaction->rollback();       
                };
            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo), $exception) ) != 'boolean'){
                return $res;
            };
        }
        return Tool::showRes(ErrMap::getError(10005));
    }

    /*删除我的消息*/
    public function actionDelMessage()
    {
        // $this->memberInfo = (object)array(
        //     'member_id' => 24
        // );
        /*如果没有登录，自动登录*/
        if(!isset($this->memberInfo)){
            Yii::$app->runAction('member/login/getinfo-by-openid');
        }

        if(isset($this->memberInfo)){
            $id = isset($this->post['id'])?$this->post['id']:'';
            if($id){
                if( MemberMessage::updateAll(['isdel' => 2], 'mid = :id', [':id' => $id]) ){//删除成功
                    $backInfo = [0, '删除我的消息成功'];//返回信息
                }else{//删除失败
                    $backInfo = ErrMap::getError(10013, '删除我的消息失败');//返回信息
                }
                //操作日志
                if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, '', $this->memberInfo), '') ) != 'boolean'){
                    return $res;
                };
            }
            return Tool::showRes(ErrMap::getError(10005));
        }else{
            list($errno, $errmsg) = ErrMap::getError(10007);
            return Tool::showRes([$errno, $errmsg]);
        }
    }

    /*获取会员消息*/
    public function actionMessageList()
    {
        // $this->memberInfo = (object)array(
        //     'member_id' => 24
        // );
        if(isset($this->memberInfo)){
            if(isset($this->get['page'])){
                $currPage = intval($this->get['page']?$this->get['page']:1);
            }else{
                $currPage = 1;
            }
            $pageSize = Tool::getPageSize();

            $memberMessage = new MemberMessage;
            $count = $memberMessage::find()
                            ->where('isdel = 1 and member_id = :mid', [':mid' => $this->memberInfo->member_id])
                            ->count();
            $memberMessageList = $memberMessage::find()
                            ->select(['mid', 'issys', 'title', 'content', 'add_time'])
                            ->where('isdel = 1 and member_id = :mid', [':mid' => $this->memberInfo->member_id])
                            ->orderBy(['mid' => SORT_DESC])
                            ->offset($pageSize*($currPage-1))->limit($pageSize)
                            ->asArray()->all();

            /*未读消息清零*/
            Member::updateAll(['unread_messages' => 0], 'member_id = :memberid', [':memberid' => $this->memberInfo->member_id]);

            /*所有的消息改为已读*/
            MemberMessage::updateAll(['isread' => 2], 'member_id = :memberid', [':memberid' => $this->memberInfo->member_id]);

            $res = array(
                'list' => $memberMessageList,
                'pageInfo' => array(
                    'count' => intval($count),
                    'currPage' => $currPage,
                    'pageSize' => $pageSize,
                ),
            );
            // p($res);
            return Tool::showRes([0, '获取成功'], $res);
        }else{
            list($errno, $errmsg) = ErrMap::getError(10007);
            return Tool::showRes([$errno, $errmsg]);
        }
    }    

}
